5. Theory Axios Read Only
Axios is a library for making HTTP requests in JavaScript, and widely used in React.
It helps to interact with API's. It helps to fetch or send data to server using built-in fetch API features like request/response , JSON data handling and error handling
Step 1: Install Axios
npm install axios
Step 2: Import Axios
import axios from 'axios';
Step 3: Make a Request
You can use Axios within useEffect to fetch data when the component mounts. Here’s an example of fetching data from an API:
i am using API form FreeApi.app
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
axios.get("https://api.freeapi.app/api/v1/public/randomproducts")
.then(response => {
setData(response.data.data.data); //as per the json data
})
.catch(err => {
setError(err);
console.log(err); // Fix: Log 'err' instead of 'error'
});
}, []);
return (
<div>
<ul>
{data.map((product) => ( //rember to use '()' as these is return brackets
<li key={product.id}>
<p>Brand: {product.brand}</p>
<p>Description: {product.description}</p>
<p>Price: ${product.price}</p>
</li>
))}
</ul>
{error && <p>Error: {error.message}</p>}
</div>
);
}
export default App;
JSON Data Format
{
"statusCode": 200,
"data": {
"page": 1,
"limit": 10,
"totalPages": 10,
"previousPage": false,
"nextPage": true,
"totalItems": 100,
"currentPageItems": 10,
"data": [
{
"id": 1,
"title": "iPhone 9",
"description": "An apple mobile which is nothing like apple",
"price": 549,
"discountPercentage": 12.96,
"rating": 4.69,
"stock": 94,
"brand": "Apple",
"category": "smartphones",
"thumbnail": "https://cdn.dummyjson.com/product-images/1/thumbnail.jpg",
"images": [
"https://cdn.dummyjson.com/product-images/1/1.jpg",
"https://cdn.dummyjson.com/product-images/1/2.jpg",
"https://cdn.dummyjson.com/product-images/1/3.jpg",
"https://cdn.dummyjson.com/product-images/1/4.jpg",
"https://cdn.dummyjson.com/product-images/1/thumbnail.jpg"
]
Key Points
- GET Request:
axios.get(url)fetches data from the server. - POST Request:
axios.post(url, data)sends data to the server. - Error Handling: Catch errors with
.catch()for better error handling. - Response Data:
response.datacontains the data returned by the API.
This basic setup covers how to use Axios for API calls in React, handling both success and error cases.